package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogParser;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.util.Optional;
import java.util.regex.Pattern;

@Slf4j
public class NginxLogParserImpl implements NginxLogParser {
    @Override
    public Optional<NginxLogItem> parse(String line) {
        val m = pattern.matcher(line);
        if (!m.matches()) {
            log.error("Error parsing line: {}", line);
            return Optional.empty();
        }
        return Optional.of(new NginxLogItem(m.group("ip"), m.group("time"), m.group("request"), m.group("status"), m.group("bytes"), m.group("referer"), m.group("ua")));
    }

    private static final Pattern pattern = Pattern.compile("(?<ip>\\d+\\.\\d+\\.\\d+\\.\\d+)\\s+-\\s+-\\s+\\[(?<time>\\d+/\\w+/\\d+:\\d+:\\d+:\\d+\\s+\\+\\d+)]\\s+\"(?<request>.*)\"\\s+(?<status>\\d+)\\s+(?<bytes>\\d+)\\s+\"(?<referer>[^\"]+)\"\\s+\"(?<ua>[^\"]+)\"");

}
